package com.myimooc.shiro.web.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @className: RolesOrFilter
 * @description: 当存在指定角色中的某一个角色时，认证通过
 * @date: 2020/5/12
 * @author: cakin
 */
public class RolesOrFilter extends AuthorizationFilter {

    /**
     * 功能描述：当数据库中存在指定角色中的某一个角色时，认证通过
     *
     * @author cakin
     * @date 2020/5/12
     * @param request 请求
     * @param response 响应
     * @param mappedValue 角色数组
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed( ServletRequest request, ServletResponse response, Object mappedValue ) throws Exception {
        Subject subject = getSubject(request, response);
        String[] roles = (String[]) mappedValue;
        if (roles == null || roles.length == 0) {
            return true;
        }
        for (String role : roles) {
            if (subject.hasRole(role)) {
                return true;
            }
        }
        return false;
    }
}
